import 'package:cream_chat_flutter/models/Ajax.dart';
import 'package:cream_chat_flutter/models/dopo/GetRecommendUserListArgs.dart';
import 'package:cream_chat_flutter/models/dopo/GetRecommendUserListDto.dart';
import 'package:cream_chat_flutter/models/dopo/UserBaseInfo.dart';
import 'package:flutter/material.dart';

class HomeTabPageProvider extends ChangeNotifier {
  static HomeTabPageProvider _instance;

  HomeTabPageProvider._() {
    print("init");
  }

  static HomeTabPageProvider getInstance() {
    if (_instance == null) {
      _instance = HomeTabPageProvider._();
    }
    return _instance;
  }

  changeTab() {
    print("HomeTabPageProvider Tab");
  }

  List<UserBaseInfo> _recommendUsers = [];

  List<UserBaseInfo> get recommendUsers => _recommendUsers;

  void setRecommendUsers(List<UserBaseInfo> list) {
    _recommendUsers = list;
    notifyListeners();
  }

  int _pageNo = 1;

  int get pageNo => _pageNo;

  void setPageNo(int pageNo) {
    _pageNo = pageNo;
  }

  int _pageSize = 50;

  int get pageSize => _pageSize;

  void setPageSize(int pageSize) {
    _pageSize = pageSize;
  }

  List<int> _ids = [];

  List<int> get ids => _ids;

  void setIdx(List<int> ids) {
    _ids = ids;
  }

  bool _hasMore = true;
  bool get hasMore => _hasMore;
  void setHasMore(bool hasMore) {
    _hasMore = hasMore;
    notifyListeners();
  }
  bool _loading = false;
  bool get loading => _loading;
  void setLoading(bool loading) {
    _loading = loading;
    notifyListeners();
  }

  void getRecommendUser(bool isRefresh) async {
    if (isRefresh) {
      setPageNo(1);
      setIdx([]);
      setHasMore(true);
    }
    if (!hasMore) return;
    setLoading(true);
    GetRecommendUserListDto dto;
    try {
      dto = await Ajax().getRecommendUserList(GetRecommendUserListArgs(
          pageNo: pageNo, pageSize: pageSize, ids: ids));
    } catch (e) {
      print('Error: $e'); // Handle the exception first.
    } finally {
      setLoading(false);
    }
    if (dto == null || dto.data == null || dto.data.list == null) return;
    if (dto.data.list.length >= pageSize) {
      _pageNo++;
    } else {
      setHasMore(false);
    }
    _recommendUsers.addAll(dto.data.list);
    setRecommendUsers(recommendUsers);
  }
}
